package com.cskaoyan.gateway.controller.promo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.controller.cache.CacheManager;
import com.google.common.util.concurrent.RateLimiter;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.promo.PromoService;
import com.mall.promo.constant.PromoRetCode;
import com.mall.promo.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;

@RestController
@RequestMapping("/shopping")
public class PromoController {

    @Reference(check = false,timeout = 3000)
    PromoService promoService;
    @Autowired
    CacheManager cacheManager;
    @Anoymous
    @GetMapping("/seckilllist")
    public ResponseData secKillList(PromoInfoRequest request){

        SimpleDateFormat yymmdd = new SimpleDateFormat("yyyyMMdd");
        //设置当前时间和当前应该显示的秒杀场次
        String dateStr = yymmdd.format(new Date());
        request.setYyyymmdd(dateStr);

        PromoInfoResponse response = promoService.getPromoList(request);
        if(!PromoRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response);
    }

    @PostMapping("/promoProductDetail")
    public ResponseData promoProductDetail(@RequestBody PromoProductDetailRequest request){
        PromoProductDetailResponse response = promoService.getPromoProductDetail(request);
        if(!PromoRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response);
    }

    @PostMapping("/seckill")
    public ResponseData secKill(@RequestBody CreatePromoOrderRequest request, HttpServletRequest servletRequest){
        RateLimiter rateLimiter = RateLimiter.create(100);
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        rateLimiter.acquire();
        CreatePromoOrderResponse response = new CreatePromoOrderResponse();
        //直接查缓存,如果缓存中有该场次商品售完信息,直接返回库存不足
        String s = cacheManager.checkCache("promo_stock_" + request.getPsId() + "_" + request.getProductId());
        if("true".equals(s)){
            response.setCode(PromoRetCode.PROMO_ITEM_STOCK_NOT_ENOUGH.getCode());
            response.setMsg(PromoRetCode.PROMO_ITEM_STOCK_NOT_ENOUGH.getMessage());
            return new ResponseUtil<>().setData(response);
        }
        String attribute = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject jsonObject = JSON.parseObject(attribute);
        Long uid = Long.parseLong(jsonObject.get("uid").toString());
        String username = (String) jsonObject.get("username");
        request.setUserId(uid);
        request.setUserName(username);
        Future<CreatePromoOrderResponse> future = executorService.submit(new Callable<CreatePromoOrderResponse>() {
            @Override
            public CreatePromoOrderResponse call() throws Exception {
                return promoService.createPromoOrder(request);
            }
        });
        try {
            response = future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        if(!PromoRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response);
    }
}
